package org.lifeyears.web.action;

import java.util.Collection;
import java.util.List;

import org.lifeyears.model.Donation;
import org.lifeyears.model.Project;
import org.lifeyears.model.User;
import org.lifeyears.services.DonationService;
import org.lifeyears.services.ProjectService;
import org.lifeyears.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * Action for displaying a user profile
 * 
 * @author Martin Aasen
 */
@Scope( "prototype" )
@Component
public class DonateAction
    extends AbstractLifeyearsAction
{
    @Autowired
    private DonationService donationService;

    @Autowired
    private UserService userService;

    @Autowired
    private ProjectService projectService;
    
    private Long userid;
    
    private Project project;

    private int lifeyears;
    
    private String donate;
    
    public int getLifeyears() {
		return lifeyears;
	}

	public void setLifeyears(int lifeyears) {
		this.lifeyears = lifeyears;
	}

	public Project getProject() {
		return project;
	}

	public void setProject(Project project) {
		this.project = project;
	}

	public void setDonationService( DonationService donationService )
    {
        this.donationService = donationService;
    }

    public void setUserService( UserService userService )
    {
        this.userService = userService;
    }

    public void setUserId( int userid )
    {
        this.userid = new Long( userid );
    }

    @Override
    public String execute()
        throws Exception
    {
    	
    	 if ( donate == null )
         {
             return INPUT;
         }

         if ( hasErrors() )
         {
             return ERROR;
         }

    	
    	System.out.println("Project: "+project+" was selected");
    	System.out.println("donate: "+donate);
    	System.out.println("Lifeyears donated: "+lifeyears);
    	
        return SUCCESS;
    }

    public User getUser()
    {
        // FIXME: Enable parameterized user, e.g. using "id" parameter or
        // similar.
        
        return (userid == null) ? getLoggedInUser() : userService.get( userid );
    }

    public int getLifeyearsSaved()
    {
        int i = 0;
        for ( Donation d : getDonations() )
        {
            i += d.getLifeyears();
        }
        return i;
    }

    public Collection<Donation> getDonations()
    {
        return donationService.getDonations( getUser() );
    }

	public void setProjectService(ProjectService projectService) {
		this.projectService = projectService;
	}
	
	public List<Project> getAvailableProjects(){
		List<Project> list = projectService.getAllList();
		System.out.println("There is a total of "+list.size()+" projects to choose from");
		return list;
	}

	public String getDonate() {
		return donate;
	}

	public void setDonate(String donate) {
		this.donate = donate;
	}

}
